import {dateFormat, transition} from '@/utils/util.js'
import {areaList} from '@vant/area-data';
// screenList
import {listArr} from './screen'
import {educationalInformationClick} from './educationalInformation'
import {deletedEmployeeFamily, deleteWorkHistoryInfo} from '@/api/Fillln'
import {Toast} from 'vant';
import {useCounterStore} from '@/pinia/user.js'
import {dispatching, regularEmployee, trainee, WorkerHourlyWorker} from './EmployeeType.js'


const checkingRule = (function () {
    const counterStore = useCounterStore()
    const b = counterStore.HireType
    return b === 'regular' ? regularEmployee() : b === 'dispatched' ? dispatching() : b === 'Hours' ? WorkerHourlyWorker() : b === 'trainee' ? trainee() : {}
})


// 删除就传回 空字符串的
const arrList = ['isCountry', 'countriesRegion', 'cityRegion', 'contactCityRegion']

export class FromList {
    constructor(obj, row) {
        this.type = obj.type
        this.name = obj.name
        this.rules = obj.rules
        this.key = obj.key
        this.placeholder = obj.placeholder
        this.show = obj.show || false
        this.disabled = obj.disabled || false
        this.value = ''
        if (+this.type === 1) {
            this.rules = obj.rules ? [{
                required: true,
                trigger: 'onBlur',
                ...obj.rules
            }] : [{
                required: true,
                trigger: 'onBlur',
                message: `请输入${this.name}`
            }]
        } else if (this.type === 2) {
            this.label = ''
            this.rules = obj.rules ? [{
                required: true,
                trigger: 'onChange',
                ...obj.rules
            }] : [{
                required: true,
                trigger: 'onChange',
                message: `请选择选择${this.name}`
            }]
            this.placeholder = `请选择${this.name}`
            this.children = obj.children
            this.showPicker = false
            this.confirm = function (value, item) {
                item.label = value.label
                item.value = value.value
                item.showPicker = false
            }
            this.deleteValue = (item) => {
                if (arrList.includes(item.key)) {
                    item.label = ''
                    item.value = ''
                } else {
                    item.label = ''
                    item.value = ''
                }

            }
        } else if (this.type === 3) {
            this.date = new Date()
            this.rules = obj.rules ? [{
                required: true,
                trigger: 'onChange',
                ...obj.rules
            }] : [{
                required: true,
                trigger: 'onChange',
                message: `请选择${this.name}时间`
            }]
            this.placeholder = `请选择${this.name}`
            this.showPicker = false
            this.confirm = function (value, item) {
                const date = new Date(value).getTime()
                const va = dateFormat(date).split(' ')
                this.value = va[0]
                // item.value = value
                item.showPicker = false
            }
            this.deleteValue = (item) => {
                item.label = ''
                item.value = ''
            }
        } else if (this.type === 4) {
            this.text = ''
            this.value = ''
            this.rules = obj.rules ? [{
                required: true,
                trigger: 'onChange',
                ...obj.rules
            }] : [{
                required: true,
                trigger: 'onChange',
                message: `请选择${this.name}`
            }]
            this.children = obj.children
            this.showPicker = false
            this.confirm = function (value, item) {
                const a = value.map(item => item.name)
                item.text = transition(a)
                item.value = transition(a)
                item.showPicker = false
            }
        } else if (this.type === 5) {
            this.class = obj.class
            this.click = function (item, list) {
                if (item.key === 'EducationInformation') {
                    educationalInformationClick(item, list)
                } else if (item.key === '') {

                } else {
                    if (item.placeholder.indexOf(item.class) !== -1) {
                        // 正在添加的家庭成员
                        return
                    } else if (item.placeholder.indexOf('添加') !== -1) {
                        // 添加家庭成员
                        addMemberFamily(item, list)
                    } else if (item.placeholder.indexOf('删除') !== -1) {
                        // 删除改家庭成员
                        deleteMemberFamily(item, list)
                    }
                }

            }
        } else if (this.type === 6) {
            this.url = obj.url
            this.query = obj.query
            this.click = function (item, list) {
                if (item.key === 'EducationInformation') {
                    educationalInformationClick(item, list)
                }
            }
        } else if (this.type === 7 || this.type === 8) {
            this.value = []
        }
        if (obj.value) {
            this.value = obj.value
        }
        if (obj.label) {
            this.label = obj.label
            obj.children.forEach(item => {
                if (item.label === obj.label) this.value = item.value
            })
        }
        if (row) {
            if (this.type === 2) {
                this.label = row[obj.key] || ''
                obj.children.forEach(item => {
                    if (item.label === this.label) this.value = item.value
                })
            } else if (this.type === 7 || this.type === 8) {
                if (row[obj.key] && row[obj.key].fileCode) {
                    this.value.push({
                        content: `data:image/jpeg;base64,${row[obj.key]?.fileCode}`,
                        fileName: row[obj.key] && row[obj.key].fileName
                    })
                }
                if (row[obj.key] && Array.isArray(row[obj.key]) && row[obj.key].length > 0) {
                    row[obj.key].forEach(item => {
                        this.value.push({
                            content: `data:image/jpeg;base64,${item?.fileCode}`,
                            fileName: item && item.fileName
                        })
                    })
                }

            } else {
                if (this.type === 4) {
                    this.value = row[obj.key]
                    this.text = row[obj.key]
                }
                this.value = row[obj.key] || ''
            }
        }
        if (this.value && this.type === 2) {
            obj.children.forEach(item => {
                if (item.value === this.value) this.label = item.label
            })
        }
        checkingRule().forEach(item => {
            if (this.key === item) {
                this.rules = []
            }
        })
        if (row && +row.isSubmit === 1) {
            this.disabled = true
        }
        return this
    }
}


// 身份证号码正则
export function IdCardRegularExpression(value) {
    if (!value) return '请输入身份证号码'
    const str = /^[1-9]\d{5}(16|17|18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    if (str.test(value)) {
        return true
    } else {
        return '格式不正确'
    }
}

export function mailboxVerification(value) {
    if (!value) return '请输入邮箱'
    const str = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (str.test(value)) {
        return true
    } else {
        return '邮箱格式不正确'
    }
}


// 银行卡号码正则  只验证位数
function CardRegularization(value) {
    if (!value) return '请输入银行卡号码'
    const str = /^[1-9]\d{9,29}$/;
    if (str.test(value)) {
        return true
    } else {
        return '格式不正确'
    }
}

// 手机号码
function MobilePhoneNumberVerification(value) {
    if (!value) return '请填写完整'
    const str = /^1[3-9]\d{9}$/
    if (str.test(value)) {
        return true
    } else {
        return '格式不正确'
    }
}

// 邮编正则  只验证位数
function postalCode(value) {
    if (!value) return '请输入有6位邮编'
    const str = /^[0-9]\d{5}$/;
    if (str.test(value)) {
        if (!repetition(value)) {
            return true
        } else {
            return '格式不正确'
        }
    } else {

        return '格式不正确'


    }
}

function repetition(value) {
    if (!value) return ''
    let a = value.split('')[0]
    let b = true
    value.split('').forEach(item => {
        if (b) b = a === item
    })
    return b
}

// 开户行
function verifyBankDeposit(value) {
    if (!value) return '请输入开户行'
    if (value.length < 6) {
        return '字数不能小于六位'
    } else {
        return true
    }
}


// 添加家庭成员
function addMemberFamily(item, list) {
    // 获取当前item 的key
    const key = +item.key + 1
    // 调整标题
    item.placeholder = `${item.class}${key}`
    // 新的一个家庭成员
    const arr = []
    // 如果是第二个的话添加删除按钮
    let a
    // 获取当前家庭成员的key
    const Number1 = item.key
    list.forEach((it, index) => {
        const b = it.key + ''
        const p = b.replace(/[^0-9]/ig, "") || 1
        if (+it.key === +Number1 || +p === +Number1) {
            const o = {...it}
            if (index > 7 && o.name) {
                o.key = o.key.substr(0, o.key.length - 1)
            }
            o.key = o.key + (key + '')
            if (!o.name && o.placeholder !== '删除') {
                a = {
                    ...o
                }
                o.placeholder = '添加'
                o.key = key
            }
            arr.push(o)
        }
    })
    arr.forEach(item => {
        if (item.type !== 999) {
            item.value = '';
            item.label = '';
            item.text = ''
        } else {
            item.value = ''
        }

    })
    list.push(...arr)
    list.forEach((i, index) => {
        if (i.placeholder === '删除') list.splice(index, 1)
    })
    a.placeholder = '删除'
    a.key = key
    item.rules = 'delete'
    list.push(a)
}

// 删除最后一个
async function deleteMemberFamily(item, list) {
    let b = ''
    let it = {}
    list.forEach(item => {
        if (item.type === 999) {
            b = item.key
            it = item
        }
    })
    if (b.includes('familyId')) {
        if (!await deletedEmployeeFamilyItem(list)) return
    } else {
        if (!await deleteWorkHistoryInfoItem(it)) return
    }


    const a = []
    const w = {
        ...list[list.length - 1]
    }
    list.forEach((it, index) => {
        const b = it.key + ''
        const p = b.replace(/[^0-9]/ig, "") || 1
        if (+p === +item.key) a.push(index)
    })
    list.splice(a[0], a.length)
    if (list.length < 10) {
        list[a[0] - 1].placeholder = '添加'
    } else {
        w.key = list[a[0] - 1].key
        list[a[0] - 1].placeholder = '添加'
        list.push(w)
    }
}

async function deletedEmployeeFamilyItem(list) {
    const CounterStore = useCounterStore()
    // deletedEmployeeFamily
    const item = list[list.length - 3]
    if (item.value) {
        const res = await deletedEmployeeFamily({
            familyId: item.value,
            id: CounterStore.employeeId
        })
        if (res.success) {
            Toast.success(res.message)
        } else {
            Toast.fail(res.message)
        }
        return res.success
    } else {
        return true
    }
}

// deleteWorkHistoryInfo
// 删除工作经历
async function deleteWorkHistoryInfoItem(item) {
    const CounterStore = useCounterStore()
    if (!item.value) return true
    const res = await deleteWorkHistoryInfo({
        workId: item.value,
        id: CounterStore.employeeId
    })
    if (res.success) {
        Toast.success(res.message)
    } else {
        Toast.fail(res.message)
    }
    return res.success
}


export async function essentialInformation(defaultValue = {}) {
    const counterStore = useCounterStore()
    const a = await listArr()
    const b = counterStore.HireType
    const c = b === 'regular' ? '正式工' : b === 'dispatched' ? '派遣' : b === 'Hours' ? '小时' : b === 'trainee' ? '应届生' : ''
    // let employeeTypeLable = ''
    // a.employeeType.forEach(item=>{ if(item.label.includes(c)) employeeTypeLable = item.value })
    // console.log(c)
    const disabledIsAttribution = !!defaultValue.isAttribution
    const arr = [
        {
            type: 2,
            name: '归属地',
            key: 'isAttribution',
            // placeholder: '真实姓名'
            children: a.isAttribution,
            disabled: disabledIsAttribution
        },
        {
            type: 2,
            name: '人员类型',
            key: 'employeeType',
            label: c,
            // placeholder: '真实姓名'
            children: a.employeeType,
            disabled: true
        }, {
            type: 2,
            name: '事件原因',
            key: 'orderType',
            // placeholder: '真实姓名'
            children: a.orderType
        }, {
            type: 1,
            name: '姓名',
            key: 'fullName',
            placeholder: '真实姓名'
        },
        {
            type: 1,
            name: '拼音首字母',
            key: 'fullNameFirst',
            // disabled: true
        }, {
            type: 2,
            name: '国家',
            key: 'isCountry',
            children: a.isCountry,
            label: '中国'
        },
        {
            type: 2,
            name: '证件类型',
            key: 'documentType',
            children: a.documentType,
            label: '居民身份证'
        },
        {
            type: 1,
            name: '证件号',
            key: 'cardId',
            rules: {
                validator: IdCardRegularExpression
            }
        },
        {
            type: 8,
            name: '证件照片',
            key: 'idCardFiles',
            placeholder: '请上传身份证照片'
        },
        {
            type: 3,
            name: '出生日期',
            key: 'birthDate',
            placeholder: '请选择出生日期'
        },
        {
            type: 2,
            name: '主要语言环境是否为中文',
            key: 'eLanguage',
            placeholder: '是否为主要语言环境',
            label: '是',
            children: a.yeNo
        },
    ]
    return arr.map(item => new FromList(item, defaultValue))
}

export async function personalDetails(defaultValue = {}) {
    const a = await listArr()
    const arr = [{
        type: 2,
        name: '性别',
        key: 'isSex',
        children: [{
            value: '男',
            label: '男'
        }, {
            value: '女',
            label: '女'
        }],
    }, {
        type: 2,
        name: '国籍',
        key: 'isNationality',
        placeholder: '请选择',
        children: a.isCountry,
        label: '中国',
    },
        {
            type: 2,
            name: '政治面貌',
            key: 'politicalOutlook',
            placeholder: '请选择',
            children: a.politicalOutlook,
        }, {
            type: 2,
            name: '婚姻状况',
            key: 'maritalStatus',
            placeholder: '请选择',
            children: a.maritalStatus,
        }, {
            type: 3,
            name: '入党日期',
            key: 'joinCpcDate',
            placeholder: '请选择',
        }, {
            type: 3,
            name: '入团日期',
            key: 'joinCcylDate',
            placeholder: '请选择',
        }, {
            type: 3,
            name: '参加工作日期',
            key: 'workDate',
            placeholder: '请选择',
        }, {
            type: 1,
            name: '银行卡号',
            key: 'bankAccount',
            placeholder: '银行卡号码',
            rules: {
                validator: CardRegularization
            }
        }, {
            type: 1,
            name: '开户行',
            key: 'accountsBank',
            placeholder: '××银行××市××支行',
            rules: {
                validator: verifyBankDeposit
            }
        }, {
            type: 1,
            name: '银行缩写',
            key: 'bankName',
            placeholder: '输入银行卡号自动带出',
            disabled: true
        },
        {
            type: 8,
            name: '银行卡附件',
            key: 'bankCardFiles',
            placeholder: '请上传银行卡照片'
        },
        {
            type: 2,
            name: '是否首次在沪缴纳社保公积金',
            key: 'whetherFirstPay',
            placeholder: '是否首次在沪缴纳社保公积金',
            children: a.traineeYeNo
        },
        {
            type: 2,
            name: '上家单位是否在沪',
            key: 'whetherCompanyLocal',
            placeholder: '上家单位是否在沪',
            children: a.yeNo
        },
        {
            type: 3,
            name: '上次单位离职年月',
            key: 'lastQuitDate',
        },
        {
            type: 2,
            name: '是否购车',
            key: 'isVehicle',
            placeholder: '请选择',
            children: a.yeNo
        },
        {
            type: 3,
            name: '购车日期',
            key: 'vehicleDate',
            placeholder: '请选择',
        }, {
            type: 2,
            name: '业内购车',
            key: 'isIndustry',
            placeholder: '请选择',
            children: a.yeNo
        },

    ]
    return arr.map(item => new FromList(item, defaultValue))
}

// 户籍信息
export async function TheHouseholdRegistrationInformation(defaultValue = {}) {
    const l = Object.keys(areaList.province_list).map(item => {
        const o = {}
        let p = ''
        if (areaList.province_list[item].includes('省')) {
            p = areaList.province_list[item].split('省')[0]

        } else if (areaList.province_list[item].split('市')) {
            p = areaList.province_list[item].split('市')[0]
        }

        if (p.length >= 3 && p !== '黑龙江') p = p.slice(0, 2)

        if (areaList.province_list[item]) {
            o.label = p
            o.value = p
        }
        return o
    })
    const a = await listArr()
    const arr = [{
        type: 2,
        name: '国家地区',
        key: 'countriesRegion',
        placeholder: '请选择',
        children: a.isCountry,
        label: '中国',
    }, {
        type: 2,
        name: '户口性质',
        key: 'registryType',
        placeholder: '请选择',
        children: a.registryType,
    }, {
        type: 2,
        name: '民族',
        key: 'nationType',
        placeholder: '请选择',
        children: a.nationType,
    }, {
        type: 1,
        name: '籍贯',
        key: 'nativePlace',
        placeholder: '请输入',
    }, {
        type: 2,
        name: '户籍',
        key: 'registryCity',
        children: l,
        placeholder: '请选择',
    }]
    return arr.map(item => new FromList(item, defaultValue))
}


// 联系信息
export async function contactWay(defaultValue = {}) {

    const a = await listArr()
    const arr = [{
        type: 2,
        name: '邮箱类型',
        key: 'emailType',
        placeholder: '请选择',
        children: a.emailType,
    }, {
        type: 1,
        name: '邮箱地址',
        key: 'emailAddress',
        placeholder: '请输入邮箱地址',
    }, {
        type: 2,
        name: '是否主要联系方式',
        key: 'mainEmail',
        label: '是',
        children: a.yeNo,
        disabled: true
    }, {
        type: 2,
        name: '电话类型',
        key: 'mobileType',
        placeholder: '请选择',
        label: '手机',
        children: a.mobileType,
        disabled: true
    }, {
        type: 1,
        name: '电话号码',
        key: 'mobileNumber',
        placeholder: '电话号码',
        children: a.mobileType,
        disabled: true
    }, {
        type: 2,
        name: '是否主要联系方式',
        key: 'mainMobile',
        label: '是',
        placeholder: '请选择',
        children: a.yeNo,
        disabled: true
    },]
    return arr.map(item => new FromList(item, defaultValue))
}

// 地址信息
export async function addressMessage(defaultValue = {}) {
    const a = await listArr()
    const arr = [{
        type: 2,
        name: '地址类型',
        key: 'addressType',
        placeholder: '请选择',
        children: a.addressType,
        label: '户籍地址',
        disabled: true
    }, {
        type: 2,
        name: '国家地区',
        key: 'cityRegion',
        placeholder: '请选择',
        label: '中国',
        children: a.isCountry,
    }, {
        type: 1,
        name: '详细地址',
        key: 'detailedAddress',
        placeholder: '请输入',
    }, {
        type: 1,
        name: '邮编',
        key: 'zipCode',
        placeholder: '请输入',
        rules: {
            validator: postalCode
        }
    }, {
        type: 2,
        name: '地址类型',
        key: 'contactAddressType',
        placeholder: '请选择',
        children: a.addressType,
        label: '联系地址',
        disabled: true
    }, {
        type: 2,
        name: '国家地区',
        key: 'contactCityRegion',
        placeholder: '请选择',
        label: '中国',
        children: a.isCountry,
    }, {
        type: 1,
        name: '详细地址',
        key: 'contactDetailedAddress',
        placeholder: '请输入',
    }, {
        type: 1,
        name: '邮编',
        key: 'contactZipCode',
        placeholder: '请输入',
        rules: {
            validator: postalCode
        }
    }]
    return arr.map(item => new FromList(item, defaultValue))
}


// 紧急联系人
export async function emergencyContact(defaultValue = {}) {
    const a = await listArr()
    const arr = [{
        type: 1,
        name: '姓名',
        key: 'emergencyContact',
        placeholder: '紧急联系人姓名',
    }, {
        type: 2,
        name: '关系',
        key: 'isRelation',
        placeholder: '请输入',
        children: a.FamilyRelation,
    }, {
        type: 1,
        name: '电话',
        key: 'contactMobile',
        placeholder: '紧急联系人电话',
        rules: {
            validator: MobilePhoneNumberVerification
        }
    }, {
        type: 2,
        name: '主要联系人',
        key: 'mainContact',
        placeholder: '请选择',
        label: '是',
        children: a.yeNo,

    }]
    return arr.map(item => new FromList(item, defaultValue))
}

// 家庭成员
export async function memberFamily(defaultValue = {}) {
    const a = await listArr()
    let arr = [{
        type: 1,
        name: '姓名',
        key: 'familyName',
        placeholder: '家庭成员姓名',
    }, {
        type: 2,
        name: '关系',
        key: 'familyRelation',
        placeholder: '请输入',
        children: a.isRelation,
    }, {
        type: 1,
        name: '拼音首字母',
        key: 'familyNameFirst',
        placeholder: '姓名首字母',
    }, {
        type: 3,
        name: '出生日期',
        key: 'familyBirthDate',
        placeholder: '请选择',
    }, {
        type: 1,
        name: '工作单位',
        key: 'workUnit',
        placeholder: '请输入工作单位',
    }, {
        type: 1,
        name: '职位',
        key: 'workPosition',
        placeholder: '请输入工作职位'
    }, {
        type: 999,
        key: 'familyId',
        name: '唯一id'
    },
        {
            class: '家庭成员',
            type: 5,
            placeholder: '添加',
            key: '1'
        }
    ]

    if (defaultValue.family && defaultValue.family.length > 0) {
        if (defaultValue.family.length > 1) {
            defaultValue.family.forEach((item, index) => {
                if (index !== 1) addMemberFamily(arr[arr.length - 1], arr)
            })

            const number = defaultValue.family.length
            const obj = {}
            const a = ['familyBirthDate', 'familyName', 'familyNameFirst', 'workUnit', 'familyRelation', 'familyId', 'workPosition']
            for (let i = 0; number > i; i++) {
                a.forEach(item => {
                    obj[`${item}${i ? 1 + i : ''}`] = defaultValue.family[i][item]
                })
            }
            defaultValue = {
                ...defaultValue,
                ...obj
            }
        } else {
            defaultValue = {
                ...defaultValue,
                ...defaultValue.family[0]
            }
        }
    }
    arr = arr.filter((item, index) => {
        if (item.placeholder !== '添加' || index === (arr.length - 2) || +item.key === 1) return item
    })
    return arr.map(item => new FromList(item, defaultValue))
}

export async function occupationalHistory(defaultValue = {}) {
    let arr = [{
        type: 3,
        name: '开始日期',
        key: 'startDate',
        placeholder: '请选择开始日期',
    }, {
        type: 3,
        name: '结束日期',
        key: 'endDate',
        placeholder: '请选择结束日期',
    }, {
        type: 1,
        name: '任职单位',
        key: 'officeCompany',
        placeholder: '请输入任职单位',
    }, {
        type: 1,
        name: '部门',
        key: 'departmentName',
        placeholder: '请输入任职部门',
    }, {
        type: 1,
        name: '岗位',
        key: 'workPostName',
        placeholder: '请输入任职岗位',
    },
        {
            type: 1,
            name: '证明人',
            key: 'workWitnessName',
            placeholder: '请输入证明人',
        }, {
            type: 999,
            key: 'workId',
            name: '唯一id'
        },
        {
            class: '工作经历',
            type: 5,
            placeholder: '添加',
            key: '1',
        }
    ]

    if (defaultValue.history && defaultValue.history.length > 0) {
        if (defaultValue.history.length > 1) {
            defaultValue.history.forEach((item, index) => {
                if (index !== 1) addMemberFamily(arr[arr.length - 1], arr)
            })

            const number = defaultValue.history.length
            const obj = {}
            const a = ['startDate', 'endDate', 'officeCompany', 'departmentName', 'workPostName', 'workWitnessName', 'workWitnessName', 'workId']
            for (let i = 0; number > i; i++) {
                a.forEach(item => {
                    obj[`${item}${i ? 1 + i : ''}`] = defaultValue.history[i][item]
                })
            }
            defaultValue = {
                ...defaultValue,
                ...obj
            }
        } else {
            defaultValue = {
                ...defaultValue,
                ...defaultValue.history[0]
            }
        }
    }
    arr = arr.filter((item, index) => {
        if (item.placeholder !== '添加' || index === (arr.length - 2) || +item.key === 1) return item
    })
    return arr.map(item => new FromList(item, defaultValue))
}
